<?php
Class EventAction extends Action {
	public function user(){//管理用户病历首页
		$user['id'] = $event['user_id']=$this->userid = intval(I('id'));
		$this->user = M('User')->where($user)->find();//当前用户的一些基本信息

		$event['pubtype'] = $this->pubtype = intval(I('pubtype',2));//1草稿2发布3屏蔽（不做物理删除）

		if($event['pubtype']==4){
			$openid = M('User')->where("id={$user['id']}")->getField('openid');
			$events = M('EventRegistration')->where("openid='{$openid}'")->field("event_id")->select();
			foreach ($events as $key => $value) {
				$eventid[]=$value['event_id'];
			}
			$ids = implode(",", $eventid);
			unset($event);
			$event['id']=array('in',$ids);
		}

		if($event['pubtype']==5){
			$events = M('EventDiscuss')->where("user_id={$user['id']} AND pubtype=1")->field("event_id")->select();
			foreach ($events as $key => $value) {
				$eventid[]=$value['event_id'];
			}
			$ids = implode(",", $eventid);
			unset($event);
			$event['event_id']=array('in',$ids);
			$event['pubtype']=1;	
		}
		if($event['pubtype']==6){
			$events = M('EventDiscuss')->where("user_id={$user['id']} AND pubtype=2")->field("event_id")->select();
			foreach ($events as $key => $value) {
				$eventid[]=$value['event_id'];
			}
			$ids = implode(",", $eventid);
			unset($event);
			$event['event_id']=array('in',$ids);
			$event['pubtype']=2;			
		}
		//导入分页插件/该层是在editurl中打开的
		import('ORG.Util.EditPage');
		$count = M('Event')->where($event)->count();
		$Page = new Page($count,10);
        $Page->setConfig('theme',"<ul class='pagination'><li><a>%totalRow% %header% %nowPage%/%totalPage% 页</a></li><li>%upPage%</li><li>%first%</li><li>%prePage%</li><li>%linkPage%</li><li>%nextPage%</li><li>%end%</li><li>%downPage%</li>".$gopagenu."</ul>");
		$this->page = $Page->show();
		if($this->pubtype<5){
       		$this->list = M('Event')->where($event)->order("id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
       	}else{
       		$this->list = M('EventDiscuss')->field('id,event_id,content,addtime,masktime')->where($event)->order("id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
       	}
        $this->currentpage = $Page->firstRow + 1; 
		$this->display();
	}

	public function edit(){
		if(IS_POST){
			$condition['id']=intval(I('id'));
			$data['cashtype']=intval(I('cashtype'));
			$data['isonline']=I('isonline');
			$data['eventlink']=intval(I('eventlink'));
			$data['location']=I('location');
			$data['price']=I('price');
			$data['name']=I('name');
			$data['period']=I('period');
			$data['starttime']=I('starttime');
			$data['endtime']=I('endtime');
			$data['major']=I('major');
			$data['partitions']=I('partitions');
			$data['membercount']=I('membercount');
			$data['conditions']=I('conditions');
			$data['description']=I('description');
			$data['schedule']=I('schedule');
			$data['traffic']=I('traffic');
			$data['tips']=I('tips');
			$searchtext = implode(" ",$data);
			$data['searchtext']=$searchtext;
			if($image = I('images')){
				$data['image'] = "./Public/static/is_pic.jpg";
				M('EventImages')->where("event_id={$condition['id']}")->delete();
				$images = explode(",",$image);
				for($i=0;$i<count($images);$i++){
					$event['image']=$images[$i];
					$event['event_id']=$condition['id'];
					M('EventImages')->add($event);				
				}
			}else{
				$data['image'] = "./Public/static/no_pic.jpg";
			}
			if($organizer=I('organizers')){
				M('EventOrganizer')->where("event_id={$condition['id']}")->delete();
				$organizers = explode(",",$organizer);
				for($i=0;$i<count($organizers);$i++){
					$eventorg['name']=$organizers[$i];
					$eventorg['event_id']=$condition['id'];
					M('EventOrganizer')->add($eventorg);				
				}				
			}
			if($contact=I('contacts')){
				M('EventContact')->where("event_id={$condition['id']}")->delete();
				$contacts = explode(",",$contact);
				for($i=0;$i<count($contacts);$i++){
					$details = explode('|',$contacts[$i]);
					$eventcont['name']=$details[0];
					$eventcont['mobile']=$details[1];
					$eventcont['email']=$details[2];
					$eventcont['event_id']=$condition['id'];
					M('EventContact')->add($eventcont);
					
				}				
			}			
			$data['savetime']=time();
			$save = M('Event')->where($condition)->save($data);
			if($save!==false){
				$this->ajaxReturn(array('status'=>1),"JSON");exit;
			}else{
				$this->ajaxReturn(array('status'=>0),"JSON");exit;
			}
		}
		$event['id']=intval(I('id'));
		$user['id']=$this->userid=intval(I('userid'));
		$this->event = M("Event")->where($event)->find();
		$this->user = M('User')->where($user)->find();
		$this->area = M('Area')->select();
		$this->images =M('EventImages')->where("event_id={$event['id']}")->select();
		$this->contact =M('EventContact')->where("event_id={$event['id']}")->select();
		$this->organizer =M('EventOrganizer')->where("event_id={$event['id']}")->select();
		$this->major = M('Major')->select();
		$this->pubtype=intval(I("pubtype"));
		$this->page=intval(I('p'));
		$this->display();
	}

	public function add(){
		if(IS_POST){
			$data['user_id']=intval(I('userid'));
			$data['cashtype']=intval(I('cashtype'));
			$data['isonline']=I('isonline');
			$data['eventlink']=intval(I('eventlink'));
			$data['location']=I('location');
			$data['price']=I('price');
			$data['name']=I('name');
			$data['period']=I('period');
			$data['starttime']=I('starttime');
			$data['endtime']=I('endtime');
			$data['major']=I('major');
			$data['partitions']=I('partitions');
			$data['membercount']=I('membercount');
			$data['conditions']=I('conditions');
			$data['description']=I('description');
			$data['schedule']=I('schedule');
			$data['traffic']=I('traffic');
			$data['tips']=I('tips');
			$data['restnums']=$data['membercount'];
			$searchtext = implode(" ",$data);
			$data['searchtext']=$searchtext;
			$data['savetime']=$data['addtime']=time();
			$add = M('Event')->add($data);
			if($add){
				if($image = I('images')){
					//$data['image'] = "./Public/static/is_pic.jpg";
					$images = explode(",",$image);
					for($i=0;$i<count($images);$i++){
						if($i==0){
							M('Event')->where("id={$add}")->save(array('image'=>$images[$i]));
						}
						$event['image']=$images[$i];
						$event['event_id']=$add;
						M('EventImages')->add($event);				
					}
				}else{
					$data['image'] = "./Public/static/no_pic.jpg";
				}
				if($organizer=I('organizers')){
					$organizers = explode(",",$organizer);
					for($i=0;$i<count($organizers);$i++){
						$eventorg['name']=$organizers[$i];
						$eventorg['event_id']=$add;
						M('EventOrganizer')->add($eventorg);				
					}				
				}
				if($contact=I('contacts')){
					$contacts = explode(",",$contact);
					for($i=0;$i<count($contacts);$i++){
						$details = explode('|',$contacts[$i]);
						$eventcont['name']=$details[0];
						$eventcont['mobile']=$details[1];
						$eventcont['email']=$details[2];
						$eventcont['event_id']=$add;
						M('EventContact')->add($eventcont);
						
					}				
				}			
				$this->ajaxReturn(array('status'=>1),"JSON");exit;
			}else{
				$this->ajaxReturn(array('status'=>0),"JSON");exit;
			}
		}
		$user['id']=$this->userid=intval(I('userid'));
		$this->user = M('User')->where($user)->find();
		$this->area = M('Area')->select();
		$this->major = M('Major')->select();
		$this->pubtype=intval(I("pubtype"));
		$this->page=intval(I('p'));
		$this->display();
	}

	public function publish(){
		$condition['id']=intval(I('id'));
		$data['pubtype']=2;
		$data['pubtime']=time();
		$data['ispass']=2;//发布进入审核状态
		$save = M('Event')->where($condition)->save($data);
		if($save!==false){
			$this->ajaxReturn(array("status"=>1),"JSON");
		}else{
			$this->ajaxReturn(array("status"=>0),"JSON");
		}
	}

	public function savetemp(){
		$condition['id']=intval(I('id'));
		$data['pubtype']=1;
		$data['savetime']=time();
		$save = M('Event')->where($condition)->save($data);
		if($save!==false){
			$this->ajaxReturn(array("status"=>1),"JSON");
		}else{
			$this->ajaxReturn(array("status"=>0),"JSON");
		}
	}

	public function getevent(){
		$condition['id']=I('id');
		$data['list'] = M('Event')->where($condition)->find();
		$data['organizer'] = M('EventOrganizer')->where("event_id={$condition['id']}")->select();
		$data['contact'] = M('EventContact')->where("event_id={$condition['id']}")->select();
		$data['image'] = M('EventImages')->where("event_id={$condition['id']}")->select();
		$this->ajaxReturn($data,"JSON");
	}

	public function getcontent(){
		$condition['id']=I('id');
		$data = M('EventDiscuss')->where($condition)->find();
		$this->ajaxReturn($data,"JSON");
	}

	public function postcontent(){
		$condition['id']=I('id');
		$data['content']=I('content');
		$save = M('EventDiscuss')->where($condition)->save($data);
		if($save!==false){
			$this->ajaxReturn(array("status"=>1),"JSON");
		}else{
			$this->ajaxReturn(array("status"=>0),"JSON");
		}
	}

	public function importevent(){
		if($filename = $this->uploadcsv()){
			$handle = fopen($filename, 'r'); 
			$result = $this->input_csv($handle); //解析csv 
			$len_result = count($result); 
			if($len_result==0){ 
			    $this->ajaxReturn(array('status'=>0,'msg'=>'没有任何数据'),"JSON");exit;
			}
		    for ($i = 1; $i < $len_result; $i++) {
		        $data['cashtype'] = iconv('gb2312', 'utf-8', $result[$i][0]); //中文转码 
		        $data['isonline'] = $result[$i][1]; 
		        $data['eventlink'] = $result[$i][2]; 
		        $data['location'] =  iconv('gb2312', 'utf-8', $result[$i][3]);
		        $data['price'] = $result[$i][4];
		        $data['name'] = iconv('gb2312', 'utf-8', $result[$i][5]);
		        $data['period'] = iconv('gb2312', 'utf-8', $result[$i][6]);
		        $data['starttime'] = $result[$i][7];
		        $data['endtime'] = $result[$i][8];
		        $data['major'] = iconv('gb2312', 'utf-8', $result[$i][9]);
		        $data['partitions'] = iconv('gb2312', 'utf-8', $result[$i][10]);
		        
		        $data['membercount'] =  $result[$i][11];
		        $data['conditions'] = iconv('gb2312', 'utf-8', $result[$i][12]);
		        $data['description'] = iconv('gb2312', 'utf-8', $result[$i][13]);
		        $data['schedule'] = iconv('gb2312', 'utf-8', $result[$i][14]);
		        $data['traffic'] = iconv('gb2312', 'utf-8', $result[$i][15]);
		        $data['tips'] = iconv('gb2312', 'utf-8', $result[$i][16]);
		        $data['image'] = "./Public/static/no_pic.jpg";//默认没有图片
		        $data['user_id']=intval(I('userid'));
		        $searchtext = implode(" ", $data);
		        //$data['level']=$result[$i][14]; 
		        $data['searchtext']=$searchtext;
		        $data['addtime']=time();//创建时间
		        $data['savetime']=time();//存草稿时间
		        $data['restnums']=$data['membercount'];
		        //$data['cashtype']=$result[$i][15]; 
		        $data['ispass']=2;//后台没有审阅过
		        if($isUser = M('User')->where("id={$data['user_id']}")->getField('id')){
			        	$add = M('Event')->add($data);
			        //插入组织和联系人
				if($organizer=iconv('gb2312', 'utf-8', $result[$i][17])){
					$organizers = explode("|",$organizer);
					for($x=0;$x<count($organizers);$x++){
						$eventorg['name']=$organizers[$x];
						$eventorg['event_id']=$add;
						M('EventOrganizer')->add($eventorg);				
					}				
				}

				if($contact=iconv('gb2312', 'utf-8', $result[$i][18])){
					$contacts = explode("||",$contact);
					for($x=0;$x<count($contacts);$x++){
						$details = explode('|',$contacts[$x]);
						$eventcont['name']=$details[0];
						$eventcont['mobile']=$details[1];
						$eventcont['email']=$details[2];
						$eventcont['event_id']=$add;
						M('EventContact')->add($eventcont);
						
					}				
				}			        
			        //
			        if(!$add){
			        	fclose($handle);
			        	$this->ajaxReturn(array('status'=>0,'msg'=>M('Event')->getLastSql()),"JSON");exit;
			        	
			        }else{
					    fclose($handle); //关闭指针 
					    $this->ajaxReturn(array('status'=>1),"JSON");exit;	
					   		        	
			        }		        	
		        }else{
			        	fclose($handle);
			        	$this->ajaxReturn(array('status'=>0,'msg'=>'用户不存在'),"JSON"); exit;	
		        }
		    } 

		}else{
			$this->ajaxReturn(array('status'=>0,'msg'=>$filename),"JSON");exit;
		}
	}

	private function uploadcsv(){
		import('ORG.Net.UploadFile');
		$upload = new UploadFile();// 实例化上传类
		//$upload->maxSize  = 3145728 ;// 设置附件上传大小
		$upload->allowExts  = array('csv');// 设置附件上传类型
		$upload->savePath =  './Public/Uploads/csv/';// 设置附件上传目录
		if(!$upload->upload()) {// 上传错误提示错误信息
			return 0;
		}else{// 上传成功 获取上传文件信息
			$info =  $upload->getUploadFileInfo();
			return $upload->savePath.$info[0]['savename'];
		}		
	}

	private function input_csv($handle){
		setlocale(LC_ALL,array('zh_CN.gbk','zh_CN.gb2312','en_US.utf8'));
	    $out = array (); 
	    $n = 0; 
	    while ($data = fgetcsv($handle, 10000)) { 
	        $num = count($data); 
	        for ($i = 0; $i < $num; $i++) { 
	            $out[$n][$i] = $data[$i]; 
	        } 
	        $n++; 
	    } 
	    return $out; 
	}
}